import router from '@/router'
import { useUserStore } from '@/stores/user'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'
// 创建axios实例
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 20000,
})
// 请求返回类型
export interface ResultAllType<T> {
  code: number
  msg: string
  data: T
}
// 请求封装
export const myRequest = <T> (url: string, method: Method, obj?: object) => {
  return service<T, ResultAllType<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: obj
  })
}
// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = useUserStore().token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    return config
  },
  error => {
    return Promise.reject(error)
  },
)
// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if(error.response){
      // 提示响应的错误信息
      ElMessage.error(error.response.data.msg)
      if (error.response.status === 401) {
        // 跳转到登录页 - 并传递当前路由的fullPath
        router.push({
          path: '/login',
          query: {
            redirect: router.currentRoute.value.fullPath // 登录页的redirect参数为当前路由的fullPath
          }
        })
        // 清除token信息
        const store = useUserStore()
        store.removeToken()
      }
    } else {
      // 无响应
      ElMessage.error('网络错误，请稍后重试')
    }
    return Promise.reject(error)
  },
)

export default service
